package com.zj.leetcode.medium;

/**
 * @program: algorithm
 * @description: 旋转链表
 * 61 rotate-list
 * @author: Zhang Bo
 * @create: 2022-01-14 17:05
 **/
public class RotateList {
    public static void main(String[] args) {
        ListNode listNode = new ListNode(1,
                new ListNode(2,
                        new ListNode(3,
                                new ListNode(4,
                                        new ListNode(5, null)))));


        ListNode head = new ListNode(1,
                new ListNode(2, null));

        Solution solution = new RotateList().new Solution();
        System.out.println(solution.rotateRight(listNode, 2));
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }


    class Solution {
        public ListNode rotateRight(ListNode head, int k) {

            if (head == null) {
                return null;
            }
            int size = (int) this.size(head);

            int point = size - k % size;

            ListNode cur = head;
            ListNode cut = null;
            ListNode last = null;
            int i = 0;
            while (cur != null) {
                i++;
                if (i == point) {
                    cut = cur;
                }

                //成环操作
                if (cur.next == null) {
                    last = cur;
                }

                cur = cur.next;
            }

            if (last != null) {
                last.next = head;
            }

            if (cut != null) {
                head = cut.next;
                cut.next = null;
            }


            return head;

        }

        public long size(ListNode head) {
            int size = 0;
            ListNode cur = head;
            while (cur != null) {
                size++;
                cur = cur.next;
            }

            return size;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}
